import common from "../../lib/common/common.js"
import fetch from "node-fetch";
import fs from 'fs';

const USER_WZID_FILE_PATH = 'data/WZRY/王者营地ID.json'
const Tutorials = 'https://raw.gitcode.com/Kevin1217/resources/files/master/resources/img/example/王者营地ID获取.png'

fs.mkdirSync('data/WZRY', { recursive: true })
if (!fs.existsSync(USER_WZID_FILE_PATH)) fs.writeFileSync(USER_WZID_FILE_PATH, JSON.stringify({}, null, 4), 'utf8')

const WZZJCX_REGEX = /^(#|\/)?战绩查询([1-9]\d*)$/
const BDWZID_REGEX = /^(#|\/)?绑定(王者|营地)(ID|id)([1-9]\d*)$/
export class example extends plugin {
    constructor() {
        super({
            name: '王者战绩查询',
            dsc: 'example',
            event: 'message',
            priority: 1,
            rule: [
                {
                    reg: WZZJCX_REGEX,
                    fnc: 'WZZJCX'
                },
                {
                    reg: BDWZID_REGEX,
                    fnc: 'BDWZID'
                },
                {
                    reg: /^(#|\/)?我的营地主页$/,
                    fnc: 'WDYDZY'
                }
            ]
        })
    }

    async WZZJCX(e) {
        const USER_ID = e.user_id

        const FILE_DATA = JSON.parse(fs.readFileSync(USER_WZID_FILE_PATH, 'utf8'))
        const USER_WZID = FILE_DATA[USER_ID]

        if (!USER_WZID) return e.reply(['您尚未绑定营地ID，请先绑定营地ID', segment.image(Tutorials)])

        const QUERY_QUANTITY = parseInt(e.msg.match(WZZJCX_REGEX)[2])

        e.reply([segment.at(USER_ID), `\n查询最近${QUERY_QUANTITY}条战绩中，请稍等...`])

        const URL_DATA = await (await fetch(`https://api.yujn.cn/api/wzzj.php?type=json&num=${QUERY_QUANTITY}&id=${USER_WZID}`)).json()
        const URL2_DATA = await (await fetch('https://www.sapi.run/hero/getHeroList.php')).json()
        const URL_CODE = URL_DATA['code']
        const URL_ZJ_DATA = URL_DATA['data']

        if (URL_CODE === 201) return e.reply([segment.at(USER_ID), '请绑定正确的营地ID，或召唤师隐藏了个人战绩.'])
        if (URL_CODE === 200) {
            if (e.adapter === 'QQBot') {
                let REPLY = []
                for (let i = 0; i < QUERY_QUANTITY; i++) {
                    const GAME_TIME = URL_ZJ_DATA[i]['gametime']
                    const GAME_RESULT = URL_ZJ_DATA[i]['result']
                    const GAME_MODE = URL_ZJ_DATA[i]['mapName']
                    const GAME_RANK = URL_ZJ_DATA[i]['roleJobName']
                    const STARS = URL_ZJ_DATA[i]['stars']
                    const GAME_DURATION = URL_ZJ_DATA[i]['time']
                    const KILLCNT = URL_ZJ_DATA[i]['killcnt']
                    const DEADCNT = URL_ZJ_DATA[i]['deadcnt']
                    const ASSISTCNT = URL_ZJ_DATA[i]['assistcnt']
                    const HERO_ID = URL_ZJ_DATA[i]['heroId']
                    let HERO = ''

                    URL2_DATA['data'].forEach(obj => {
                        if (obj.ename === HERO_ID) {
                            HERO = obj.cname
                        }
                    })

                    let GANE_EVALUATION = URL_ZJ_DATA[i]['desc']
                    if (GANE_EVALUATION === '') GANE_EVALUATION = '无'

                    REPLY.push([
                        `# 对局时间: ${GAME_TIME}`,
                        `> ${GAME_MODE} [${GAME_RESULT}] 时长: ${GAME_DURATION}分钟`,
                        `使用英雄：${HERO}`,
                        `战绩：${KILLCNT}/${DEADCNT}/${ASSISTCNT}`,
                        `评价：${GANE_EVALUATION}`,
                        `段位：${GAME_RANK} ${STARS}星`
                    ])
                }

                return e.reply(REPLY)
            } else {
                let REPLY = []
                for (let i = 0; i < QUERY_QUANTITY; i++) {
                    const GAME_TIME = URL_ZJ_DATA[i]['gametime']
                    const GAME_RESULT = URL_ZJ_DATA[i]['result']
                    const GAME_MODE = URL_ZJ_DATA[i]['mapName']
                    const GAME_RANK = URL_ZJ_DATA[i]['roleJobName']
                    const STARS = URL_ZJ_DATA[i]['stars']
                    const GAME_DURATION = URL_ZJ_DATA[i]['time']
                    const KILLCNT = URL_ZJ_DATA[i]['killcnt']
                    const DEADCNT = URL_ZJ_DATA[i]['deadcnt']
                    const ASSISTCNT = URL_ZJ_DATA[i]['assistcnt']
                    const HERO_ICON = URL_ZJ_DATA[i]['heroIcon']

                    let GANE_EVALUATION = URL_ZJ_DATA[i]['desc']
                    if (GANE_EVALUATION === '') GANE_EVALUATION = '无'

                    REPLY.push([
                        `对局时间：${GAME_TIME}`,
                        `\n对局模式：${GAME_MODE}`,
                        `\n对局时长：${GAME_DURATION}分钟`,
                        `\n战绩：${KILLCNT}/${DEADCNT}/${ASSISTCNT}`,
                        `\n对局结果：${GAME_RESULT}`,
                        `\n对局评价：${GANE_EVALUATION}`,
                        `\n段位：${GAME_RANK} ${STARS}星`,
                        '\n使用英雄',
                        segment.image(HERO_ICON)
                    ])
                }

                return e.reply(await common.makeForwardMsg(e, REPLY, `${USER_WZID}的最近${QUERY_QUANTITY}局对局信息`));
            }
        }
    }

    async BDWZID(e) {
        const USER_ID = e.user_id
        const FILE_DATA = JSON.parse(fs.readFileSync(USER_WZID_FILE_PATH, 'utf8'))
        const WZID = parseInt(e.msg.match(BDWZID_REGEX)[4])
        FILE_DATA[USER_ID] = WZID
        fs.writeFileSync(USER_WZID_FILE_PATH, JSON.stringify(FILE_DATA, null, 4), 'utf8')
        return e.reply([segment.at(USER_ID), `绑定成功，营地ID：${WZID}`])
    }

    async WDYDZY(e) {
        const USER_ID = e.user_id
        const FILE_DATA = JSON.parse(fs.readFileSync(USER_WZID_FILE_PATH, 'utf8'))
        const USER_WZID = FILE_DATA[USER_ID]

        if (!USER_WZID) return e.reply(['您尚未绑定营地ID，请先绑定营地ID', segment.image(Tutorials)])

        const URL_DATA = await (await fetch(`https://api.yujn.cn/api/wzyd.php?type=json&id=${USER_WZID}`)).json()
        const URL_CODE = URL_DATA['code']
        const YD_ID = URL_DATA['userId']
        const GAME_NICKNAME = URL_DATA['roleName']
        const IP = URL_DATA['ip']
        const GAME_RANK = URL_DATA['roleJobName']
        const START = URL_DATA['rankingStar']
        const GAME_LEVEL = URL_DATA['level']
        const GAME_AREA = URL_DATA['areaName']
        const GAME_SERVER = URL_DATA['serverName']
        const GAME_COMBAT_POWER = URL_DATA['fighting']
        const TOTAL_BATTLE_COUN = URL_DATA['totalBattleCoun']
        const GAME_MVP = URL_DATA['mvpNum']
        const WINNING_PERCENTAGE = URL_DATA['winRate']
        const heroNum = URL_DATA['heroNum']
        const skinNum = URL_DATA['skinNum']

        if (URL_CODE === 201) return e.reply([segment.at(USER_ID), '请绑定正确的营地ID'])
        if (URL_CODE === 200) {
            return e.reply([
                `营地ID：${YD_ID}`,
                `\nIP：${IP}`,
                `\n游戏昵称：${GAME_NICKNAME}`,
                `\nLV.${GAME_LEVEL}`,
                `\n段位：${GAME_RANK} ${START}星`,
                `\n${GAME_AREA}${GAME_SERVER}`,
                `\n战斗力：${GAME_COMBAT_POWER}`,
                `\n总场次：${TOTAL_BATTLE_COUN}`,
                `\nMVP：${GAME_MVP}`,
                `\n胜率：${WINNING_PERCENTAGE}`,
                `\n英雄：${heroNum}`,
                `\n皮肤：${skinNum}`
            ])
        }
    }
}